angular.module('manager.controllers', ['sale-roles.services'])
.controller('AppCtrl', function($scope,$rootScope,$location,$meteor,$state) {
	$rootScope.hasFilter = false;
	$rootScope.showEdit=false;
	$rootScope.isEdit = false;
	$rootScope.toggleEdit=function(){ //callback
		$rootScope.isEdit=!$rootScope.isEdit;
	};
	$rootScope.isFirstLogin = !!$location.search().firstLogin;

})
.controller('HomeCtrl', function($scope, SalesService) {
	$scope.$on('$ionicView.enter', function(e) {
		var conditions = {
			'date':{"$gt":moment().startOf('day').toDate()}
		};
		SalesService.analytic($scope,conditions,function(data){
			$scope.saleAnalytics=data;
		});

		SalesService.getOrderCountMonthly($scope);
		SalesService.getOrderCountAll($scope);
	});
})

.controller('PerformanceCtrl', function($scope,SalesService) {
	$scope.pageTitle = "店铺业绩";
	$scope.$on('$ionicView.enter', function(e) {
		SalesService.getPerformance($scope,function(data){
			$scope.myPreformance=data;
		});
	});
})

.controller('filterController', function($scope,$rootScope) {
	$rootScope.showFilter = function() {
		$rootScope.filterShow = !$rootScope.filterShow;
	};
	$rootScope.filterDate = function(date) {
		$rootScope.filterShow = !$rootScope.filterShow;
	};
})


// 开销售单
.controller('CreateSaleOrderCtrl', function($scope,$ionicModal,$cordovaBarcodeScanner,$state) {
	var productsSubHandle = $scope.subscribe('products');
	$scope.helpers({
		products: function() {
			return Products.find({});
		}
	});

	$scope.autorun(function(){
		if(productsSubHandle.ready() && $scope.products){
			$scope.title = '全部商品';
			// 获取品牌列表
			$scope.brandList = {};
			$scope.products.forEach(function(product) {
				product.final_price = product.sale_price;
				if(!$scope.brandList[product.properties.brand.value]){
					$scope.brandList[product.properties.brand.value]=1;
				}else{
					$scope.brandList[product.properties.brand.value]+=1;
				}
				return;
			});
		}
	});
	// 隐藏顾客信息
	$scope.isBlockShown=false;
	$scope.toggleFeilds = function(){
		$scope.isBlockShown = !$scope.isBlockShown;
	};

	$scope.scanBarcode = function() {
	    $cordovaBarcodeScanner.scan().then(function(imageData) {
	        alert(imageData.text);
	        console.log("Barcode Format -> " + imageData.format);
	        console.log("Cancelled -> " + imageData.cancelled);
	    }, function(error) {
	        console.log("An error happened -> " + error);
	    });
	};

	$ionicModal.fromTemplateUrl('templates/product/select-sale-order.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.productsModal = modal;
	});

	$scope.$on('$destroy', function() {
		$scope.productsModal.remove();
	});

	// 显隐分类
	$scope.toggleCat=function(){
		$scope.showCat = ! $scope.showCat;
	};
	// 显隐价格数量
	$scope.toggleItem = function(item) {
		if ($scope.isItemShown(item)) {
		  $scope.shownItem = null;
		} else {
		  $scope.shownItem = item;
		}
	};
	$scope.isItemShown = function(item) {
		return $scope.shownItem === item;
	};

	$scope.order={
		price_type:'零售',
		customer:{},
		total_count:0,
		amount:0,
		list:[],
	};

	$scope.selectProduct = function(product){
		var index = $scope.order.list.indexOf(product);
		if(index == -1){
			product.count=1;
			$scope.order.list.push(product);
		}else{
			$scope.order.list.splice(index,1);
		}

	};

	$scope.minusCount = function(product){
		if(product.count>=2){
			product.count--;
		}
	};
	$scope.addCount = function(product){
		product.count++;
	};

	$scope.$watch('order.list', function(newValue, oldValue) {
		$scope.order.amount=0;
		$scope.order.total_count = 0;
	    angular.forEach(newValue, function(item, key) {
	    	if(!item.count || item.count<1){
	    		item.count = 1;
	    	}
	    	$scope.order.amount+=item.final_price * item.count;
	    	$scope.order.total_count+=item.count;
	    });
	},true);

	$scope.create = function(){
		$scope.order.list.forEach(function(s){
        	s.$$hashKey=undefined;
        });

		Meteor.call('createSaleOrder', $scope.order, function(error){
			if (error) {
				console.log(error);
			} else {
				$scope.productsModal.remove();
				$state.go('app.home');
			}
		});
	};

})

// 历史销售单
.controller('SaleOrderListCtrl', function($scope, $stateParams, SalesService) {
	$scope.listTitle = $stateParams.title?$stateParams.title:"历史";

	var fields = {};
	if($stateParams.startTime){
		fields = {date:{"$gt":new Date($stateParams.startTime),"$lt":new Date($stateParams.endTime)}};
	}
	SalesService.list($scope,fields);  // 返回 saleOrdersList
})


// 历史销售单
.controller('SaleOrderDetailCtrl', function($scope,$stateParams) {
	var saleOrdersSubHandle = $scope.subscribe('sale_orders');
	$scope.$on('$ionicView.enter', function(e) {

	$scope.helpers({
		theOrder: function() {
			return SaleOrders.findOne({'_id':$stateParams._id});
		}
	});
});
	$scope.autorun(function(){
		if(saleOrdersSubHandle.ready() && $scope.saleOrders){

		}
	});
})

// 调货单
.controller('TransferProductsCtrl', function($scope) {
	var productsSubHandle = $scope.subscribe('products');
	$scope.helpers({
		products: function() {
			return Products.find({});
		}
	});

	$scope.autorun(function(){
		if(productsSubHandle.ready() && $scope.products){
			$scope.title = '全部商品';
			// 获取品牌列表
			$scope.brandList = {};
			$scope.products.forEach(function(product) {
				product.final_price = product.sale_price;
				if(!$scope.brandList[product.properties.brand.value]){
					$scope.brandList[product.properties.brand.value]=1;
				}else{
					$scope.brandList[product.properties.brand.value]+=1;
				}
				return;
			});
		}
	});

	$scope.toggleCat=function(){
		$scope.showCat = ! $scope.showCat;
	};

	$scope.toggleItem = function(item) {
    if ($scope.isItemShown(item)) {
      $scope.shownItem = null;
    } else {
      $scope.shownItem = item;
    }
  };
  $scope.isItemShown = function(item) {
    return $scope.shownItem === item;
  };
  $scope.count=1;
  $scope.minusCount = function(){
	$scope.count=$scope.count<2?1:$scope.count-1;
  };
  $scope.addCount = function(){
  	$scope.count=$scope.count+1;
  };

  $scope.selectedProducts=[];
  $scope.selectProduct = function(product){
  	var index = $scope.selectedProducts.indexOf(product);
	if(index === -1){
		$scope.selectedProducts.push(product);
	}else{
		$scope.selectedProducts.splice(index,1);
	}
  };
})


.controller('QueryResultCtrl', function($scope) {

})



.controller('TransferListCtrl', function($scope) {

})



.controller('TransferDetailCtrl', function($scope) {

})








.controller('CreateReturnCtrl', function($scope) {
 $scope.setReturnType=function(type){
 	$scope.returnType = type;
 };
});
